<?php


declare(strict_types=1);

namespace ImiApp\ApiServer\Common;

use Imi\Cache\CacheManager as Cache;
use Imi\Cache\Handler\Redis;
// use Imi\Redis\RedisHandler;

/**
 * Token操作类
 */
class TokenRedis 
{
    protected static $options = [
        'host'        => '127.0.0.1',
        'port'        => 6379,
        'password'    => '',
        'select'      => 0,
        'timeout'     => 0,
        'expire'      => 0,
        'persistent'  => false,
        'userprefix'  => 'up:',
        'tokenprefix' => 'tp:',
    ];

    protected static $config = [
        // 驱动方式
        'type'     => 'Redis', //'Mysql',
        // 缓存前缀
        'key'      => 'VOdJPruHeNBR3sQAiXCo8Sq0awEMFfTG',
        // 加密方式
        'hashalgo' => 'sha1',//ripemd160
        // 缓存有效期 0表示永久缓存
        'expire'   => 30 * 24 * 3600,
        // 服务器地址
        'host'  => '127.0.0.1',
        // 端口
        'port'  => 6379,
        // 无密码则空
        'password'  => '8622efe3bada2cc2',

    ];
    protected static $handler;

    /**
     * 构造函数
     * @param array $options 缓存参数
     * @throws \BadFunctionCallException
     * @access public
     */
    public function __construct($options = [])
    {
        self::$handler = new Redis();
    }

    /**
     * 获取加密后的Token
     * @param string $token Token标识
     * @return string
     */
    protected static function getEncryptedToken($token)
    {
        return self::$options['tokenprefix'] . hash_hmac(self::$config['hashalgo'], $token, self::$config['key']);
    }

    /**
     * 获取会员的key
     * @param $user_id
     * @return string
     */
    protected static function getUserKey($user_id)
    {
        return self::$options['userprefix'] . $user_id;
    }

    /**
     * 存储Token
     * @param   string $token   Token
     * @param   int    $user_id 会员ID
     * @param   int    $expire  过期时长,0表示无限,单位秒
     * @return bool
     */
    public static function set($token, $user_id, $expire = 0)
    {
        if (is_null($expire)) {
            $expire = self::$options['expire'];
        }
        if ($expire instanceof \DateTime) {
            $expire = $expire->getTimestamp() - time();
        }
        $key = self::getEncryptedToken($token);
        if ($expire) {
            $result = self::$handler->set($key, $user_id,$expire);
        } else {
            $result = self::$handler->set($key, $user_id);
        }
        //写入会员关联的token
        self::$handler->sAdd(self::getUserKey($user_id), $key);
        return $result;
    }

    /**
     * 获取Token内的信息
     * @param   string $token
     * @return  array
     */
    public static function get($token)
    {
        $key = self::getEncryptedToken($token);
        $value = self::$handler->get($key);
        if (is_null($value) || false === $value) {
            return [];
        }
        //获取有效期
        $expire = self::$handler->ttl($key);
        $expire = $expire < 0 ? 365 * 86400 : $expire;
        $expiretime = time() + $expire;
        //解决使用redis方式储存token时api接口Token刷新与检测因expires_in拼写错误报错的BUG
        $result = ['token' => $token, 'user_id' => $value, 'expiretime' => $expiretime, 'expires_in' => $expire];

        return $result;
    }

    /**
     * 判断Token是否可用
     * @param   string $token   Token
     * @param   int    $user_id 会员ID
     * @return  boolean
     */
    public static function check($token, $user_id)
    {
        $data = self::get($token);
        return $data && $data['user_id'] == $user_id ? true : false;
    }

    /**
     * 删除Token
     * @param   string $token
     * @return  boolean
     */
    public static function delete($token)
    {
        $data = self::get($token);
        if ($data) {
            $key = self::getEncryptedToken($token);
            $user_id = $data['user_id'];
            self::$handler->delete($key);
            // self::$handler->sRem($this->getUserKey($user_id), $key);
        }
        return true;

    }

    /**
     * 删除指定用户的所有Token
     * @param   int $user_id
     * @return  boolean
     */
    public static function clear($user_id)
    {
        $keys = self::$handler->sMembers($this->getUserKey($user_id));
        self::$handler->delete($this->getUserKey($user_id));
        self::$handler->delete($keys);
        return true;
    }

}
